<!DOCTYPE html>
<html>

<head>
    <title>阿里云图片上传</title>
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="./Base64.js"></script>
</head>

<body>
    <div class="container" style="padding: 100px;">
        <form id="form1" enctype="multipart/form-data">
            <legend>阿里云图片上传</legend>
            <div class="form-group">
                <input type="hidden" class="form-control" id="name" name="name" value="">
                <input type="hidden" class="form-control" id="key" name="key" value="image/Temp/ApprovalTask/${filename}">
                <input type="hidden" class="form-control" id="policy" name="policy" value="">
                <input type="hidden" class="form-control" id="OSSAccessKeyId" name="OSSAccessKeyId" value="LTAI3M6GxA5Cvfev">
                <input type="hidden" class="form-control" id="success_action_status" name="success_action_status" value="200">
                <input type="hidden" class="form-control" id="signature" name="signature" value="ORlRS5Sfk6m55AcxUN0+/JDuk2c=">
                <label for="file">选择要上传的图片</label>
                <input type="file" class="btn btn-default" name="file" id="file" onchange="fileSelected();" />
            </div>
            <div class="form-group">
                <ul class="list-group">
                    <li id="fileName" class="list-group-item">Name:</li>
                    <li id="fileSize" class="list-group-item">Size:</li>
                    <li id="fileType" class="list-group-item">Type:</li>
                </ul>
            </div>
            <div class="form-group">
                <input type="button" class="btn btn-primary" onclick="uploadFile()" value="上传" />
            </div>
            <div id="progressNumber"></div>
            <div class="form-group">
                <h4 id="srcA"></h4>
                <img id="img" src="" alt="">
            </div>
        </form>
    </div>
    <script type="text/javascript">

    var fileDate    //防止多次提交

    window.onload = function() {


        var policyText = {
            "expiration": "2020-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
            "conditions": [
                ["content-length-range", 0, 1048576000] // 设置上传文件的大小限制
            ]
        };

        //加密
        var policyBase64 = new Base64().encode(JSON.stringify(policyText))

        $("policy").value = policyBase64;

    }

    //随机字符串
    function random_string(len) {　　
        len = len || 32;　　
        var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';　　
        var maxPos = chars.length;　　
        var pwd = '';　　
        for (i = 0; i < len; i++) {　　
            pwd += chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    }

    //ID选择器
    function $(str) { return document.getElementById(str); }

    //选择图片 获取图片信息
    function fileSelected() {

        var file = $('file').files[0];

        if (file) {
            var fileSize = 0;
            if (file.size > 1024 * 1024) fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
            else fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
            $('fileName').innerHTML = 'Name: ' + file.name;
            $('fileSize').innerHTML = 'Size: ' + fileSize;
            $('fileType').innerHTML = 'Type: ' + file.type;
        }

        $('name').value = file.name;

        var ramdomName = random_string(10) + $('file').value.match(/\.?[^.\/]+$/);

        $('key').value = $('key').value.replace("${filename}", ramdomName);

    }

    //发送请求上传图片
    function uploadFile() {

        //没有数据和重复数据 不能提交
        if ($('file').files[0] != undefined && fileDate != $('file').files[0]) {

            fileDate = $('file').files[0];

            var fd = new FormData($('form1'));
            var xhr = new XMLHttpRequest();
            xhr.upload.addEventListener("progress", uploadProgress, false);
            xhr.addEventListener("load", uploadComplete, false);
            xhr.addEventListener("error", uploadFailed, false);
            xhr.addEventListener("abort", uploadCanceled, false);
            xhr.open("POST", "http://flm158.oss-cn-shanghai.aliyuncs.com");
            xhr.send(fd);
        }

    }

    //进度条
    function uploadProgress(evt) {
        if (evt.lengthComputable) {
            var percentComplete = Math.round(evt.loaded * 100 / evt.total);
            $('progressNumber').innerHTML = '上传完成：' + percentComplete.toString() + '%';
        } else { $('progressNumber').innerHTML = 'unable to compute'; }
    }

    //上传完成
    function uploadComplete(evt) { /* This event is raised when the server send back a response */ console.log(evt.target.responseText);
        $('img').src = 'http://flm158.oss-cn-shanghai.aliyuncs.com/'+$('key').value;
        $('srcA').innerHTML = '访问地址：http://flm158.oss-cn-shanghai.aliyuncs.com/'+$('key').value;
     }

    //上传失败
    function uploadFailed(evt) { alert("There was an error attempting to upload the file."); }

    function uploadCanceled(evt) { alert("The upload has been canceled by the user or the browser dropped the connection."); }
    </script>
</body>

</html>